package com.wowangz.cms.syscore.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.wowangz.cms.common.utils.SysConstant;

public class XssFilter implements Filter {
	FilterConfig filterConfig = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//设置HttpOnly安全
		HttpServletRequest req = (HttpServletRequest) request;  
        HttpServletResponse resp = (HttpServletResponse) response;
		Cookie[] cookies = req.getCookies(); 
        if (cookies != null) {  
                Cookie cookie = cookies[0];  
                if (cookie != null) {
                    String value = cookie.getValue();
                    StringBuilder builder = new StringBuilder();
                    builder.append("JSESSIONID=" + value + "; ");
                    builder.append("HttpOnly; ");
                    resp.setHeader("Set-Cookie", builder.toString());
                }
        }
		//设置跨站脚本xss攻击
		String contentFilter = request.getParameter("contentFilter");
		if(StringUtils.isNotEmpty(contentFilter) && SysConstant.YesOrNo.NO == Long.valueOf(contentFilter))
		{
			chain.doFilter(request, response);
		}else
		{
			chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
		}
	}
}
